/* 工具包 */
function birthdayHandle (date) {
  let year = date.getFullYear() + ''
  let month = date.getMonth() + 1 + ''
  let day = date.getDate() + ''
  if (month.length < 2) {
    month = '0' + month
  }
  if (day.length < 2) {
    day = '0' + day
  }
  return `${year}-${month}-${day}`
}

function datetimeFormat (date) {
  let year = birthdayHandle(date)
  let m = date.getMinutes() + ''
  let h = date.getHours() + ''
  if (m.length < 2) {
    m = '0' + m
  }
  if (h.length < 2) {
    h = '0' + h
  }
  return `${year} ${h}:${m}`
}

function getWeekDate (time) {
  const dateOfToday = time ? new Date(time).valueOf() : Date.now()
  const dayOfToday = time ? (new Date(time).getDay() + 7 - 1) % 7 : (new Date().getDay() + 7 - 1) % 7
  return Array.from(new Array(7))
    .map((_, i) => {
      const date = new Date(dateOfToday + (i - dayOfToday) * 1000 * 60 * 60 * 24)
      return String(date.getFullYear()).padStart(4, '0') +
        '/' +
        String(date.getMonth() + 1).padStart(2, '0') +
        '/' +
        String(date.getDate()).padStart(2, '0')
    })
}

function file2base64 (file, callback) {
  let reader = new FileReader()
  reader.onload = (ev) => {
    callback(ev.currentTarget.result)
  }
  reader.readAsDataURL(file)
}

function validatePhone (phone) {
  let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
  return reg.test(phone)
}

function getDayIndexInYear (t) {
  let y, m, d
  let total = 0
  let arr = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  y = t.getFullYear()
  m = t.getMonth() + 1
  d = t.getDate()
  for (let i = 0; i < m - 1; i++) {
    total = total + arr[i]
  }
  if ((y % 400 === 0 || (y % 4 === 0 && y % 100 !== 0)) && m > 2) {
    total = total + d + 1
  } else {
    total = total + d
  }
  return total
}
// 给定的日期是今年的第几周
function getWeekIndexInYear (t) {
  var date1 = getDayIndexInYear(t) // 给定的日期是本年的第几天
  var _t = new Date() // 复制对象，以免修改覆盖。
  _t.setYear(t.getFullYear())
  _t.setMonth(t.getMonth())
  _t.setDate(t.getDate())

  _t.setMonth(0)
  _t.setDate(1)

  var d = _t.getDay() // 1. 得到今年的1月1号是星期几。
  var fisrtWeekned = d
  if (d === 0) {
    fisrtWeekned = 1 // 1号就是星期天,第一周的周未是1号
  } else {
    fisrtWeekned = 7 - d + 1 // 第一周的周未是几号
  }
  if (date1 <= fisrtWeekned) {
    return 1
  } else {
    return 1 + Math.ceil((date1 - fisrtWeekned) / 7)
  }
}

function randomString () {
  let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  let maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < 8; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

export {
  birthdayHandle,
  getWeekDate,
  datetimeFormat,
  file2base64,
  validatePhone,
  getWeekIndexInYear,
  randomString
}
